package com.xsh.controller;


import com.github.pagehelper.PageInfo;
import com.xsh.pojo.Role;
import com.xsh.pojo.User;
import com.xsh.service.RoleService;
import com.xsh.service.UserService;
import com.xsh.utils.GetClassUtils;
import com.xsh.utils.R;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Controller
@CrossOrigin("http://localhost:8082")
@RequestMapping("/role")
public class RoleController {

    private UserService userService = GetClassUtils.getExactClass("userServiceImpl", UserService.class);

    private RoleService roleService = GetClassUtils.getExactClass("roleServiceImpl", RoleService.class);

    @GetMapping("/list")
    @ResponseBody
    public R list(String order, Integer limit, Integer offset){
        PageInfo<Role> pageInfo = roleService.findByPageInfo(order, limit, offset);
        return R.ok().put("total", pageInfo.getTotal()).put("rows", pageInfo.getList());
    }

    @PostMapping("/save")
    @ResponseBody
    public R save(@RequestBody Role role){
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipal();
        User user = userService.findByUsername(username);
        role.setCreateUserId(user.getUserId());
        role.setCreateTime(new Date());
        roleService.addRole(role);
        return R.ok();
    }

    @GetMapping("/info/{roleId}")
    @ResponseBody
    public R roleInfo(@PathVariable Integer roleId){
        Role role = roleService.findByRoleId(roleId);
        return R.ok().put("role", role);
    }

//roleId: 5, roleName: "管理员", remark: "sdf", createUserId: null, createTime: 1508061957000,
//   menus:
    @PostMapping("/update")
    @ResponseBody
    public R update(@RequestBody Role role){
        roleService.updateRole(role);
        return R.ok();
    }

    @DeleteMapping("/del/{roleId}")
    @ResponseBody
    public R delete(@PathVariable Integer roleId) {
        roleService.deleteRole(roleId);
        return R.ok();
    }
}
